import {
  downloadFile,
  getExtensionRootPath,
  loadJsxFile,
  methodEvaler,
} from '../../core/common'
import { join } from 'path'
import { HostType } from '../../constants/common'
import { ImportOption, JPEGSaveOption, PNGSaveOption } from '../../types/type'
import { isHttpPath } from '../../utils/utils'
import { existsSync } from 'fs-extra'
import { Document } from './reflection/Document'

const _evalMethod = methodEvaler(HostType.ai)

/**
 * 初始化, 所有ai下api需要在初始化后使用
 *
 * @export
 */
export async function init () {
  const jsxPath = join(getExtensionRootPath(), './jsx/ai')
  console.log('init jsx', jsxPath)
  await loadJsxFile(jsxPath)
  return _evalMethod('ping') // 检查是否初始化成功
}

/**
 * 引入单个文件
 * @param {string} value
 * @returns string
 */
export async function openFile (
  value: string,
  options?: ImportOption
) {
  let filePath
  if (typeof value === 'string') {
    if (isHttpPath(value)) {
      filePath = await downloadFile(value, options?.tempFilePath)
    } else if (existsSync(value)) {
      filePath = value
    } else {
      throw new Error(`The file is not exist: ${value}`)
    }
  } else {
    // fake 处理
    filePath = ''
  }
  const documentItem = await _evalMethod('open', filePath)
  return documentItem
}

/**
 * 导出文件
 * @param {string | FileJson} value
 * @returns 
 */
export async function saveAsPNG (
  filePath: string,
  options?: PNGSaveOption
) {
  await _evalMethod('saveAsPNG', filePath, options)
  return filePath
}

/**
 * 导出文件
 * @param {string | FileJson} value
 * @returns 
 */
export async function saveAsJPEG (
  filePath: string,
  options?: JPEGSaveOption
) {
  await _evalMethod('saveAsJPEG', filePath, options)
  return filePath
}


export async function getActiveDocument () {
  const doc = await _evalMethod('getActiveDocument')
  return new Document(doc)
}